package com.feicheng.common.task;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.BitwiseComparison;
import com.feicheng.TimeSlotGenerator;
import com.feicheng.common.exception.SystemException;
import com.feicheng.persistence.entity.AOrder;
import com.feicheng.persistence.service.IAOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class BackOrderCofTask {

    @Autowired
    Cache cache;

    @Autowired
    IAOrderService iaOrderService;

    @Scheduled(cron = "0 0 0 * * ?") // cron 表达式：秒 分 时 日 月 周
    public void runDailyTask() {

        synchronized (cache) {
            // 清空缓存
            cache.clear();

            // 从AOrder表中取出未来7天所有的预定记录
            LocalDateTime st = LocalDateTime.now();
            LocalDateTime et = st.plusDays(7L);
            QueryWrapper<AOrder> qw = new QueryWrapper<>();
            qw.ge("st", st);
            qw.le("et", et);
            List<AOrder> orders = iaOrderService.list(qw);

            if (orders == null || orders.size() == 0) {
                throw new SystemException("未来七天没有预约");
            }

            // 按房间进行分组
            for (Iterator<AOrder> it = orders.iterator(); it.hasNext(); ) {
                AOrder order = it.next();

                if (!cache.containsKey(order.getRoomid())) {
                    cache.put(order.getRoomid(), new JSONObject());
                }

                // 当前订单对应的房间的缓存对象
                JSONObject roomCache = cache.getJSONObject(order.getRoomid());

                // 按日期分组
                JSONObject currentDateTemp = TimeSlotGenerator.generateTimeSlots(order.getSt(), order.getEt());

                for (Iterator<Map.Entry<String, Object>> ittemp = currentDateTemp.entrySet().iterator();
                     ittemp.hasNext(); ) {
                    Map.Entry<String, Object> entry = ittemp.next();

                    String dateKey = entry.getKey();
                    String dateStr = entry.getValue().toString();

                    if (roomCache.containsKey(dateKey)) {
                        String currentDateStr = roomCache.getString(dateKey);
                        String resultDateStr = BitwiseComparison.compareBits(dateStr, currentDateStr);
                        roomCache.put(dateKey, resultDateStr);
                    } else {
                        roomCache.put(dateKey, dateStr);
                    }
                }
            }
        }
    }
}
